import type { TreeDataItem } from 'ant-design-vue/es/tree';

import type { Reactive, Ref } from 'vue';
import { onBeforeMount, reactive, ref, watch } from 'vue';

import { getDeptListApi } from '#/api';
import { antTreeFilter, antTreeHandler } from '#/utils/antTools';

export default function useTreeHook(
  fetchTableData: () => Promise<void> | void,
  treeExpandedKeys: Reactive<(number | string)[]>,
  treeSelectedKeys: Ref<(number | string)[]>,
) {
  // tree节点搜索
  const treeSearchValue = ref<string>('');
  // tree 数据
  const treeData = reactive<TreeDataItem[]>([]);
  const defaultTreeData = reactive<TreeDataItem[]>([]);
  const fetchTreeData = () => {
    getDeptListApi({}).then((res) => {
      const arr2tree = antTreeHandler(res, 'dept_id', 'dept_name', 'parent_id');
      treeExpandedKeys.push(...arr2tree.map((r) => r.key));
      Object.assign(treeData, arr2tree);
      defaultTreeData.splice(0, defaultTreeData.length, ...arr2tree);
    });
  };
  const onTreeExpand = (
    keys: (number | string)[],
    e: { expanded: boolean; node: TreeDataItem },
  ) => {
    let mergedKeys = [...new Set(treeExpandedKeys)];
    if (mergedKeys.includes(e.node.key)) {
      mergedKeys = mergedKeys.filter((item) => item !== e.node.key);
      treeExpandedKeys.splice(0, treeExpandedKeys.length, ...mergedKeys);
    } else {
      // 合并 + 去重
      mergedKeys = [...new Set([e.node.key, ...keys, ...treeExpandedKeys])];
      // 清空并替换为 mergedKeys
      treeExpandedKeys.splice(0, treeExpandedKeys.length, ...mergedKeys);
    }
  };

  const onTreeSelect = (
    keys: (number | string)[],
    e: { node: TreeDataItem; selected: boolean },
  ) => {
    treeSelectedKeys.value = keys;
    let mergedKeys = [...new Set(treeExpandedKeys)];
    if (mergedKeys.includes(e.node.key)) {
      mergedKeys = mergedKeys.filter((item) => item !== e.node.key);
      treeExpandedKeys.splice(0, treeExpandedKeys.length, ...mergedKeys);
    } else {
      // 合并 + 去重
      mergedKeys = [...new Set([e.node.key, ...keys, ...treeExpandedKeys])];
      // 清空并替换为 mergedKeys
      treeExpandedKeys.splice(0, treeExpandedKeys.length, ...mergedKeys);
    }
    fetchTableData();
  };

  onBeforeMount(() => {
    fetchTreeData();
  });
  // 监听搜索框变化
  watch(treeSearchValue, (value) => {
    if (value) {
      const filterTreeData = antTreeFilter(treeData, value);
      treeData.splice(0, treeData.length, ...filterTreeData);
    } else {
      treeData.splice(0, treeData.length, ...defaultTreeData);
    }
  });
  return { treeSearchValue, treeData, onTreeExpand, onTreeSelect };
}
